<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\Customer\UserResource;
use App\Service\MiniWorkService;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login','loginMini']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
         $app=new MiniWorkService();
         $result=$app->jscode2session($request->code);
         if($result['errcode']==0){
            $user=  User::where('userid',$result['userid'])->first();
            if (!$user){
                $user=new User();
                $user->userid=$result['userid'];
            }
                $user->session_key=$result['session_key'];
                 $user->save();
         }
        if (! $token = auth('api')->login($user)) {
            return response()->json(['code' => 'error','message'=>'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginMini(Request $request){


     $user=User::where('tiyan',1)->first();
     //    $user=User::find(669);

        if (! $token = auth('api')->login($user)) {

            return response()->json(['code' => 'error','message'=>'Unauthorized'], 401);
        }
        return $this->respondWithToken($token);
    }
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $user=auth('api')->user();
        $user['permission']=  $user->getAllPermissions();

        return new UserResource($user);
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {

        return response()->json([
            'code'=>'success',
            'message'=>'登录成功',
             'data'=>   [
            'access_token' => $token,
            'token_type' => 'bearer',

        ]]);
    }
}
